package com.example.everying.framework.websocket.handler;

import com.alibaba.fastjson2.JSONObject;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.framework.websocket.utils.WebSocketRedisUtil;
import jakarta.annotation.PostConstruct;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
@Component
public class HeartbeatHandler implements MessageHandler{


    private static WebSocketRedisUtil webSocketRedisUtil;

    @Autowired
    private void setService(WebSocketRedisUtil webSocketRedisUtil) {
        HeartbeatHandler.webSocketRedisUtil = webSocketRedisUtil;
    }
    /**
     * @param session
     * @param message
     */
    @Override
    public void handle(Session session, JSONObject message) {
//        log.info("心跳检测");
        String userId = WebSocketChatService.getUserId(session);
//        log.debug(" 收到心跳检测: {}", userId);
        // 更新活跃时间
        if (userId != null) {
            // 每次消息都更新活跃时间（含心跳应答）
            // 每次更新活跃时间时，仍然设置全局TTL（防极端情况）
            webSocketRedisUtil.updateUserActivity(userId);
        }
        // 返回心跳响应
        JSONObject response = new JSONObject();
        response.put("type",  "heartbeat");
        response.put("timestamp",  System.currentTimeMillis());

        WebSocketChatService.sendHeartbeatMessageToUserId(userId,  response.toJSONString());
    }

}
